package deliciouse.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import deliciouse.dao.NewsDao;
import deliciouse.entity.News;

public class NewsDaoImpl implements NewsDao {
	private static class NewsRowMapper implements RowMapper<News>{
		public News mapRow(ResultSet rs) throws SQLException {
			News n = new News();
			n.setId(rs.getInt("id"));
			n.setTitle(rs.getString("title"));
			n.setContent(rs.getString("content"));
			n.setPublishdate(rs.getDate("publishdate"));
			n.setUserId(rs.getInt("userId"));
			return n;
		}
	}
	
	private JdbcTemplate db =new JdbcTemplate();
	public List<News> getall() {
		return db.queryList("select* from news", new NewsRowMapper());
	}
	@Override
	public List<News> fetchByDate(int pageNum, int pageSize) {
		String sql = "select * from news order by publishdate desc limit ?,?";
		return db.queryList(sql, new NewsRowMapper(), (pageNum-1)*pageSize,pageSize	);
	}
	@Override
	public int MessageMaxRows() {
		int rows =0;
		String sql ="select count(*) from news";
		return rows= (int) db.query(sql, new RowMapper<Object>() {
			public Object mapRow(ResultSet rs) throws SQLException {
				return	rs.getInt(1);
			}
		});
	}
	@Override
	public News fetchById(int id) {
		String sql = "select * from news where id=?";
		return db.query(sql, new NewsRowMapper(), id);
	}
	@Override
	public List<News> fetchByCondition(String title) {
		String sql = "select * from news where 1=1";
		ArrayList parameters = new ArrayList();
		if(title!=null){
			sql+=" and title like ?";
			parameters.add("%" + title + "%");
		}
		return db.queryList(sql, new NewsRowMapper(), parameters.toArray());
	}
	@Override
	public boolean updateNews(String title,String content,Date publishdate,int id) {
		ArrayList parameters = new ArrayList();
		String sql= "update news set title=? ,content=? ,publishdate=? where id=?";
		parameters.add(title);
		parameters.add(content);
		parameters.add(publishdate);
		parameters.add(id);
		db.executeUpdate(sql, parameters.toArray());
		return true;
	}
	@Override
	public boolean addnews(String title,String content,Date publishdate) {
		ArrayList parameters = new ArrayList();
		String sql = "insert into news(title,content,publishdate) values(?,?,?) ";
		parameters.add(title);
		parameters.add(content);
		parameters.add(publishdate);
		db.executeUpdate(sql, parameters.toArray());
		return true;
	}
	@Override
	public boolean deletenews(int id) {
		String sql = "delete from news where id=?";
		
		db.executeUpdate(sql, id);
		return true;
	}


}
